﻿(function ($) {
    var panels = {};

    $.popupPanel = function (button, panel) {
        var $panel = $(panel);

        if (panels[$panel.selector]) return;
        else {
            panels[$panel.selector] = {
                target: $panel,
                isOpening: false
            };
        }

        $(button).on("click", function () {
            var newState = $panel.css('display') == 'none' ? 'block' : 'none';

            panels[$panel.selector].isOpening = newState == 'block';
            if (panels[$panel.selector].isOpening) {
                $panel.fadeIn('slow');
            }
        });
    };

    $(document).click(function () {
        $.each(panels, function (selector, panel) {
            if (!panel.isOpening) {
                if (panel.target.css('display') != 'none') {
                    panel.target.fadeOut('slow');
                }
            }
            panel.isOpening = false;
        });        
    });
})(jQuery);